/**
 * 地址管理控制器模块
 * 
 * 处理地址增删改查(CRUD)操作的业务逻辑
 */
const AddressService = require('../services/userAddress.service');
const CustomError = require('../utils/CustomError');
const logger = require('../utils/logger');

async function getAllAddresses(req, res) {
  logger.debug("获取地址列表");
  
  // 从查询参数中获取userId（必选）
  const { userId } = req.query;
  
  // 验证userId参数
  if (!userId) {
    throw new CustomError(400, '用户ID不能为空');
  }
  
  // 记录过滤条件
  logger.debug(`根据用户ID过滤: ${userId}`);
  
  //从服务层获取地址列表，支持userId过滤
  const addresses = await AddressService.getAllAddresses(userId);

  //返回结果
  res.json({
    code: 200,
    message: "获取地址列表成功",
    data: addresses.map((address) => address.toJSON())
  });
}

async function getAddressById (req, res) {
  //从请求参数中获取地址id
  const id = req.params.id;

  logger.debug(`获取地址 ID: ${id}`);
  //调用地址服务层，获取地址信息
  const address = await AddressService.getAddressById(id);

  //业务上可预期的错误，我们需要优雅地处理
  //如果地址不存在，抛出404错误
  if (!address) {
    throw new CustomError(404, '地址不存在');
  }
     
  res.json(
    { 
      code: 200,
      message: "获取地址信息成功",
      data: address.toJSON() 
    }
  );
}

async function createAddress (req, res) {
  //打印请求参数
  logger.debug("创建地址");
  logger.debug("请求体", req.body);
  //从请求参数中获取地址信息
  const { 
    userId, 
    receiverName, 
    receiverPhone, 
    provinceName, 
    cityName, 
    districtName, 
    provinceCode, 
    cityCode, 
    districtCode, 
    detail, 
    defaultAddress 
  } = req.body;

  //校验必要参数
  if (!userId) {
    throw new CustomError(400, '用户ID不能为空');
  }

  if (!receiverName || receiverName.trim() === "" || receiverName.length > 50) {
    throw new CustomError(400, '收货人姓名不能为空，且不能超过50个字符');
  }

  if (!receiverPhone || receiverPhone.trim() === "" || receiverPhone.length > 20) {
    throw new CustomError(400, '收货人手机号不能为空，且不能超过20个字符');
  }

  if (!provinceName || provinceName.trim() === "" || provinceName.length > 20) {
    throw new CustomError(400, '省份不能为空，且不能超过20个字符');
  }

  if (!cityName || cityName.trim() === "" || cityName.length > 20) {
    throw new CustomError(400, '城市不能为空，且不能超过20个字符');
  }

  if (!districtName || districtName.trim() === "" || districtName.length > 20) {
    throw new CustomError(400, '区/县不能为空，且不能超过20个字符');
  }

  if (!detail || detail.trim() === "" || detail.length > 255) {
    throw new CustomError(400, '详细地址不能为空，且不能超过255个字符');
  }

  //对数据进行处理
  let defaultAddressValue = defaultAddress || 0;
  if(defaultAddress !== undefined && !(defaultAddress === 0 || defaultAddress === 1)) {
    defaultAddressValue = 0;
  }

  //调用地址服务层，创建地址
  const address = await AddressService.createAddress({
    userId,
    receiverName,
    receiverPhone,
    provinceName,
    cityName,
    districtName,
    provinceCode: provinceCode || null,
    cityCode: cityCode || null,
    districtCode: districtCode || null,
    detail,
    defaultAddress: defaultAddressValue
  });

  //状态201表示资源创建成功，返回创建的地址信息
  res.status(200).json(
    { 
      code: 201,
      message: "地址创建成功",
      data: address.toJSON() 
    }
  )
}

async function updateAddress (req, res)  {
  //打印请求参数
  logger.debug("更新地址");
  logger.debug("请求体", req.body);
  //从请求参数中获取地址信息
  const { id } = req.params;

  //从服务层获取地址信息
  let address = await AddressService.getAddressById(id);
  if (!address) {
    //抛出404错误,表示地址不存在
    throw new CustomError(404, '地址不存在');
  }
  
  //获取请求参数
  const { 
    userId,
    receiverName, 
    receiverPhone, 
    provinceName, 
    cityName, 
    districtName, 
    provinceCode, 
    cityCode, 
    districtCode, 
    detail, 
    defaultAddress 
  } = req.body;

  //校验参数
  if (receiverName === null 
      || (receiverName !== undefined 
          && (receiverName.trim() === "" || receiverName.length > 50))) {
    throw new CustomError(400, '收货人姓名不能为空，且不能超过50个字符');
  }

  if (receiverPhone !== undefined && (receiverPhone.trim() === "" || receiverPhone.length > 20)) {
    throw new CustomError(400, '收货人手机号不能超过20个字符');
  }

  if (provinceName !== undefined && (provinceName.trim() === "" || provinceName.length > 20)) {
    throw new CustomError(400, '省份不能为空，且不能超过20个字符');
  }

  if (cityName !== undefined && (cityName.trim() === "" || cityName.length > 20)) {
    throw new CustomError(400, '城市不能为空，且不能超过20个字符');
  }

  if (districtName !== undefined && (districtName.trim() === "" || districtName.length > 20)) {
    throw new CustomError(400, '区/县不能为空，且不能超过20个字符');
  }

  if (detail !== undefined && (detail.trim() === "" || detail.length > 255)) {
    throw new CustomError(400, '详细地址不能为空，且不能超过255个字符');
  }

  //对地址状态进行校验
  if(defaultAddress !== undefined && !(defaultAddress === 0 || defaultAddress === 1)) {
    throw new CustomError(400, '地址默认状态错误');
  }

  //更新地址信息
  address.userId = userId || address.userId;
  address.receiverName = receiverName || address.receiverName;
  address.receiverPhone = receiverPhone === undefined ? address.receiverPhone : receiverPhone;
  address.provinceName = provinceName || address.provinceName;
  address.cityName = cityName || address.cityName;
  address.districtName = districtName || address.districtName;
  address.provinceCode = provinceCode === undefined ? address.provinceCode : provinceCode;
  address.cityCode = cityCode === undefined ? address.cityCode : cityCode;
  address.districtCode = districtCode === undefined ? address.districtCode : districtCode;
  address.detail = detail || address.detail;
  address.defaultAddress = defaultAddress === undefined ? address.defaultAddress : defaultAddress;

  logger.debug("地址对象", address);
  logger.debug("收货人姓名:" + address.receiverName);

  //调用地址服务层，更新地址信息
  address = await AddressService.updateAddress(address);

  logger.debug("更新后的地址信息:");
  logger.debug(address);
  
  //返回更新后的地址信息
  res.json(
    { 
      code: 200,
      message: "地址更新成功",
      data: address.toJSON() 
    }
  );
}

async function deleteAddress(req, res){
  //打印请求参数
  logger.debug("删除地址");
  logger.debug("请求参数", req.params);
  //从请求参数中获取地址id
  const { id } = req.params;

  //从服务层获取地址信息
  const address = await AddressService.getAddressById(id);

  if (!address) {
    //抛出404错误,表示地址不存在
    throw new CustomError(404, '地址不存在');
  }

  //调用地址服务层， 删除地址
  await AddressService.deleteAddressById(id);
  //返回成功信息
  res.json(
    { 
      code: 200,
      message: "地址删除成功",
      data: {}
    }
  );
}

module.exports = {
  //导出地址控制器方法
  getAllAddresses,
  getAddressById,
  createAddress,
  updateAddress,
  deleteAddress
}